﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.Web.Modules;
using NopSolutions.NopCommerce.Controls;

namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
    public partial class ProductBundles : BaseNopAdministrationUserControl
    {
        private readonly IProductService _productService;

        public ProductBundles() {
            _productService = IoC.Resolve<IProductService>();
        }

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            gvBundles.PageIndexChanging += new GridViewPageEventHandler(gvBundles_PageIndexChanging);
            gvBundles.RowDataBound += new GridViewRowEventHandler(gvBundles_RowDataBound);

            gvProducts.RowDataBound += new GridViewRowEventHandler(gvProducts_RowDataBound);
            gvProducts.PageIndexChanging += new GridViewPageEventHandler(gvProducts_PageIndexChanging);

            btnDelete.Click += new EventHandler(btnDelete_Click);
            btnAddToBundle.Click += new EventHandler(btnAdd_Click);

            Load += new EventHandler(ProductBundles_Load);
        }

        void ProductBundles_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                if (Bundles != null && Bundles.Count > 0) {
                    btnDelete.Enabled = true;
                }
                else {
                    btnDelete.Enabled = false;
                }

                BindData();
            }
        }

        #region Methods

        private void BindData() {
            BindBundles();
            BindProducts();
        }

        private void BindBundles() {
            if (Bundles != null && Bundles.Count > 0) {
                gvBundles.Visible = true;
                gvBundles.DataSource = Bundles;
                gvBundles.DataBind();
            }
            else {
                gvBundles.Visible = true;
            }
        }

        private void BindProducts() {
            int totalRecords = 0;
            var products = _productService.GetAllProducts(gvProducts.PageSize, gvProducts.PageIndex, out totalRecords);
            if (products != null && products.Count > 0) {
                gvProducts.Visible = true;
                gvProducts.DataSource = products;
                gvProducts.DataBind();
            }
            else {
                gvProducts.Visible = false;
            }
        }

        private void SaveData() {
            // nothing ... we do it like they do on the discovery channel.
        }

        #endregion

        #region Properties

        public int ProductId { get { return CommonHelper.QueryStringInt("ProductId"); } }
        public IList<Bundle> Bundles {
            get {
                return _productService.GetAllBundlesByProductId(ProductId);
            }
        }

        #endregion

        #region Events

        void gvBundles_PageIndexChanging(object sender, GridViewPageEventArgs e) {
            gvBundles.PageIndex = e.NewPageIndex;
            BindBundles();
        }

        void gvBundles_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow) {
                var bundle = e.Row.DataItem as Bundle;
                if (bundle != null) {
                    var litProduct = e.Row.FindControl("litProduct") as Literal;
                    litProduct.Text = bundle.ProductVariant.Product.Name;

                    var ddlProductVariants = e.Row.FindControl("ddlProductVariants") as DropDownList;
                    ddlProductVariants.DataSource = _productService.GetProductVariantsByProductId(bundle.ProductId);
                    ddlProductVariants.DataTextField = "Name";
                    ddlProductVariants.DataValueField = "ProductVariantId";
                    ddlProductVariants.DataBind();
                    ddlProductVariants.SelectedValue = bundle.ProductVariantId.ToString();

                    var hfProductVariant = e.Row.FindControl("hfProductVariant") as HiddenField;
                    hfProductVariant.Value = bundle.ProductVariantId.ToString();

                    var txtQuantity = e.Row.FindControl("txtQuantity") as NumericTextBox;
                    txtQuantity.Value = bundle.Quantity;

                    var txtDisplayOrder = e.Row.FindControl("txtDisplayOrder") as NumericTextBox;
                    txtDisplayOrder.Value = bundle.Order;
                }
            }
        }

        void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e) {
            gvProducts.PageIndex = e.NewPageIndex;
            BindProducts();
        }

        void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow) {
                var product = e.Row.DataItem as Product;
                if (product != null) {
                    var chkProduct = e.Row.FindControl("chkProduct") as CheckBox;
                    var litProductName = e.Row.FindControl("litProductName") as Literal;

                    litProductName.Text = Server.HtmlEncode(product.LocalizedName);

                    var ddlProductVariant = e.Row.FindControl("ddlProductVariant") as DropDownList;
                    ddlProductVariant.DataSource = _productService.GetProductVariantsByProductId(product.ProductId);
                    ddlProductVariant.DataTextField = "Name";
                    ddlProductVariant.DataValueField = "ProductVariantId";
                    ddlProductVariant.DataBind();
                }
            }
        }

        void btnAdd_Click(object sender, EventArgs e) {
            bool addSome = false;

            foreach (GridViewRow row in gvProducts.Rows) {
                var chkProduct = row.FindControl("chkProduct") as CheckBox;
                if (chkProduct != null && chkProduct.Checked) {
                    var ddlProductVariant = row.FindControl("ddlProductVariant") as DropDownList;
                    if (ddlProductVariant != null) {
                        var productVariantId = int.Parse(ddlProductVariant.SelectedItem.Value);
                        Bundle bundle = new Bundle { ProductId = ProductId, Order = 1, Quantity = 1, ProductVariantId = productVariantId };
                        _productService.InsertBundle(bundle);
                        addSome = true;
                    }
                }
            }

            if (addSome) {
                ShowMessage("Successfully added product variants to bundle.");
                BindBundles();
                btnDelete.Enabled = true;
            }
        }

        void btnDelete_Click(object sender, EventArgs e) {
            bool deleteSome = false;

            foreach (GridViewRow row in gvBundles.Rows) {
                var hfProductVariant = row.FindControl("hfProductVariant") as HiddenField;
                if (hfProductVariant != null) {
                    var chkProduct = row.FindControl("chkProduct") as CheckBox;
                    if (chkProduct != null && chkProduct.Checked) {
                        var productVariantId = int.Parse(hfProductVariant.Value);
                        _productService.DeleteBundle(ProductId, productVariantId);
                        deleteSome = true;
                    }
                }
            }

            if (deleteSome) {
                ShowMessage("Successfully deleted product variant(s) from bundle.");
                BindBundles();
            }
        }

        #endregion
    }
}